//
// Created by wei.yang on 2021/9/6.
//
#include <iostream>
#include "socket_client.h"

using namespace std;

/**
 * 连接服务器
 * @return
 */
int SocketClient::connectServer() {

//    struct  hostent* host =  gethostby
    //套接字文件描述符
    sock_fd = socket(AF_INET, SOCK_STREAM, 0);
    if (sock_fd < 0) {
        cout << "获取套接字文件描述符失败" << endl;
        return -1;
    }

    //填充数据
    serv_addr.sin_family = AF_INET;
    serv_addr.sin_port = htons(SERVER_PORT);
    serv_addr.sin_addr = *((struct in_addr *) host->h_addr);
    bzero(&(serv_addr.sin_zero), 8);

    //发起对服务器的连接
    int ret = connect(sock_fd, (struct sockaddr *) &serv_addr, sizeof(struct sockaddr));
    if (ret < 0) {
        cout << "发起对服务器的连接失败" << endl;
        return -1;
    }

    cout << "发起对服务器的连接成功" << endl;

    return 0;
}

/**
 * 发送消息
 * @return
 */
int SocketClient::sendMsg(char *data) {
    send_bytes = send(sock_fd, data, sizeof(data), 0);
    if (send_bytes < 0) {
        cout << "发送消息成功" << endl;
        return -1;
    }
    cout << "发送消息失败" << endl;
    return 0;
}

/**
 * 接收服务端返回的消息
 * @return
 */
int SocketClient::receiveMsg(char *data) {

}

/**
 * 关闭连接
 * @param sock_fd 套接字文件描述符
 * @return
 */
int SocketClient::close() {
    int ret = ::close(sock_fd);
    if (ret < 0) {
        cout << "关闭连接失败" << endl;
        return -1;
    }
    cout << "关闭连接成功" << endl;
    return 0;
}